package com.example.a2306_shop.detail

import android.R.attr.bitmap
import android.animation.Animator
import android.animation.Animator.AnimatorListener
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.widget.ImageView
import androidx.appcompat.app.ActionBar.LayoutParams
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.a2306_shop.R
import com.example.a2306_shop.adapter.CommentAdapter
import com.example.a2306_shop.databinding.ActivityDetailBinding
import com.example.lib_base.mvvm.BaseActivity
import com.example.lib_base.param.CreateOrder
import com.example.lib_base.param.OrderDetail
import com.example.user.GlideUtils
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.OptionPicker
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.google.zxing.BarcodeFormat
import com.journeyapps.barcodescanner.BarcodeEncoder
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage


@Route(path = "/app/DetailActivity")
class DetailActivity : BaseActivity<ActivityDetailBinding,DetailViewModel>() {
    val imgs = mutableListOf<String>()
    @Autowired
    @JvmField
    var pid:Int = 1
    //定义一个属性id  当页面加载完成后进行赋值
    var attrId = ""

    lateinit var commentAdapter: CommentAdapter

    var amount = ""
    @SuppressLint("MissingInflatedId")
    override fun initData() {
        viewModel.detailSuccess.observe(this){
            if(it.code==200){
                amount = "合计:￥${it.data.productInfo.price}"
                binding.info = it.data.productInfo
                imgs.add(it.data.productInfo.image)
                imgs.add(it.data.productInfo.image)
                binding.imgs = imgs
                //设置选中的规格
                binding.tvAttrName.text = "已选择:${it.data.productValue.keys.toList()[0]}"
                //给attrId进行赋值
                attrId = it.data.productValue.values.toList()[0].id.toString()
            }
        }
        //添加购物车监听
        viewModel.addSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                val imageView = ImageView(this)
                val layoutParams = LayoutParams(200, 200)
                imageView.layoutParams = layoutParams
                GlideUtils.loadNormal(this,imgs[0],imageView)
                binding.main.addView(imageView)
                //设置动画
                val width = windowManager.defaultDisplay.width.toFloat()
                val height = windowManager.defaultDisplay.height.toFloat()

                val translationX = ObjectAnimator.ofFloat(imageView, "translationX", 0f, width)
                val translationY = ObjectAnimator.ofFloat(imageView, "translationY", 0f, height)
                val animatorSet = AnimatorSet()
                animatorSet.duration = 2000
                animatorSet.play(translationX).with(translationY)
                animatorSet.start()
                animatorSet.addListener(object :AnimatorListener{
                    override fun onAnimationStart(animation: Animator) {
                    }
                    override fun onAnimationEnd(animation: Animator) {
                        binding.main.removeView(imageView)
                    }
                    override fun onAnimationCancel(animation: Animator) {

                    }
                    override fun onAnimationRepeat(animation: Animator) {
                    }
                })


            }
        }
        //点击返回图标，结束当前界面
        binding.ivBack.setOnClickListener {
            finish()
        }
        //点击分享，弹出alertDialog  其中显示要分享的二维码 （图片路径）点击确定分享，弹出分享框，跳转到分享界面
        binding.ivShare.setOnClickListener {
            val view = LayoutInflater.from(this).inflate(R.layout.diy_share, null)
            //生成二维码
            val encodeBitmap =
                BarcodeEncoder().encodeBitmap(imgs[0], BarcodeFormat.QR_CODE, 200, 200)
            //将二维码显示到view上
           view.findViewById<ImageView>(R.id.iv).setImageBitmap(encodeBitmap)

            AlertDialog.Builder(this)
                .setTitle("图片二维码")
                .setView(view)
                .setPositiveButton("分享"){
                    a,b->

                    val image: UMImage = UMImage(this, encodeBitmap) //bitmap文件
                    ShareAction(this)
                        .setPlatform(SHARE_MEDIA.QQ)//传入平台
                        .withText("hello")//分享内容
                        .withMedia(image)//将分享的图片文件设置进去
                        .setCallback(object:UMShareListener{
                            override fun onStart(p0: SHARE_MEDIA?) {

                            }

                            override fun onResult(p0: SHARE_MEDIA?) {

                            }

                            override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
                                ToastUtils.showLong(p1?.message.toString())
                            }

                            override fun onCancel(p0: SHARE_MEDIA?) {

                            }
                        })//回调监听器
                        .open();
                }
                .setNegativeButton("取消"){
                    a,b->
                }
                .show()
        }
        viewModel.commentSuccess.observe(this){
            if(it.code==200){
                commentAdapter.data.clear()
                commentAdapter.data.addAll(it.data.list)
                commentAdapter.notifyDataSetChanged()
            }
        }
        viewModel.createSuccess.observe(this){
            if(it.code==200){
                ARouter.getInstance().build("/app/PayActivity").withString("orderNo",it.data.orderNo)
                    .withString("amount",amount).navigation()
            }
        }
    }

    override fun initView() {
        ARouter.getInstance().inject(this)
        viewModel.detail(pid,"normal")

        //点击加入购物车 ，调用加入购物车接口
        binding.tvAddCar.setOnClickListener {
            viewModel.addCart(1,attrId,pid)
        }

        //实例化评论
        commentAdapter = CommentAdapter()
        binding.rvComment.adapter = commentAdapter
        binding.rvComment.layoutManager = LinearLayoutManager(this)

        viewModel.comment(pid,10,1,"0")
        //点击立即下单，调用创建订单接口
        binding.tvBuyNow.setOnClickListener {
            val createOrder = CreateOrder()
            //详情页购买 只能买一种商品  但是依然存在list集合中
            val list = mutableListOf<OrderDetail>()
            val orderDetail = OrderDetail()
            orderDetail.productId = pid
            orderDetail.productNum = 1
            orderDetail.attrValueId =pid
            list.add(orderDetail)

            createOrder.orderDetails = list

            viewModel.orderCreate(createOrder)
        }
        //点击客服，弹时间选择框
        binding.tvKf.setOnClickListener {
            val datePicker = DatePicker(this)
            datePicker.setTitle("请选择出生年月日")
            datePicker.wheelLayout.setRange(DateEntity.target(1900,1,1), DateEntity.today(),
                DateEntity.today())
            datePicker.setOnDatePickedListener { year, month, day ->
                ToastUtils.showLong("$year-$month-$day")
            }
            datePicker.show()
        }
        //点击shoucan，弹出选项框
        binding.tvCollect.setOnClickListener {
            val list = mutableListOf("男","女")
            val optionPicker = OptionPicker(this)
            optionPicker.setTitle("请选择性别")
            optionPicker.setData(list)
            optionPicker.setOnOptionPickedListener { position, item ->
                ToastUtils.showLong("您的性别是${list[position]}")
            }
            optionPicker.show()
        }
    }

    override fun getViewModel(): Class<DetailViewModel> = DetailViewModel::class.java

    override fun getLayout(): Int = R.layout.activity_detail

}